import dayjs from "dayjs";
import { cloudAxios } from "../axios.js";
import { URL, DICT, STATUS } from "../config.js";
import {
  loginUtil,
  inputUtils,
  commonUtil,
  IDCardUtils,
} from "../../../utils/index.js";
import { chineseMedicineAdapter } from "../adapter/common/chineseMedicine.js";
import { initData, setData } from "../adapter/common/constants/initData.js";

const { setPersonStatusAndNote, setStatusAndNote } = commonUtil;

const { CHINESE_MEDICINE_DICT, CHINESE_MEDICINE_DICT_INVERT } =
  commonUtil.getInvertDict(DICT, "CHINESE_MEDICINE_DICT");

const main = async () => {
  const excelName = await commonUtil.selectExcel();
  const personList = commonUtil.excelToJson(
    excelName,
    CHINESE_MEDICINE_DICT_INVERT
  );
  await inputUtils.input({
    dataList: personList,
    fn: input,
    loginFn: loginUtil.cloudLogin,
    DICT: CHINESE_MEDICINE_DICT,
    excelName,
  });
};

async function input(person, { hisConfigSession, unieap }) {
  person.IDNum = IDCardUtils.formatIDNum(person.IDNum);
  const originPerson = { ...person };
  const currentPerson = await getPersonByIDNum(person.IDNum, {
    hisConfigSession,
  });
  if (currentPerson === null)
    return setPersonStatusAndNote(originPerson, STATUS.NOT_BUILD);
  const existedChineseMedicine = await getExistedChineseMedicine(
    currentPerson.code,
    person.assessdate
  );
  if (existedChineseMedicine) {
    const dataStores = await getDataStore(existedChineseMedicine.chid);
    await deleteChineseMedicine(dataStores);
  }

  const personStore = await getPersonInfo(currentPerson.code);
  const guideArr = await getGuideArr();
  const res = chineseMedicineAdapter(
    person,
    currentPerson.code,
    guideArr,
    hisConfigSession
  );

  const mainDataStore = [res._mainDataStore];
  const detailDataStore = res._detailDataStore;
  const guideDataStore = res._guideDataStore;

  const reqData = setData(initData, {
    personInfo: personStore,
    mainDataStore,
    detailDataStore,
    guideDataStore,
  });

  const res1 = await createChineseMedicine(reqData);
  return { ...originPerson, ...res1 };
}

// 根据身份证查询居民列表
async function getPersonByIDNum(IDNum, { hisConfigSession }) {
  const data = {
    header: { code: 0, message: { title: "", detail: "" } },
    body: {
      dataStores: {
        "felder_main_list.mainGridStore": {
          rowSet: { primary: [], filter: [], delete: [] },
          name: "felder_main_list.mainGridStore",
          pageNumber: 1,
          pageSize: 15,
          recordCount: 0,
          parameters: {
            _qf: {
              healthorg: "",
              persondivision: "",
              idnumber: IDNum,
              btnQuery: "查询",
              selfName: "",
              card: "",
              btnReset: "重置",
              seloption: null,
              personalhealth: null,
              donevisitFrom: "",
              donevisitTo: "",
              donevisittypeType: "",
              cardstatus: "1",
              yearService: null,
              visitFrom: "",
              visitTo: "",
              visittypeType: "",
              btnMore: "更多条件",
              unitcode: hisConfigSession.Chisunitcode,
              unittype: hisConfigSession.OrgType, // 未确定是否正确
            },
          },
        },
      },
      parameters: {
        _IABONAME: "fhrElderIABO",
        _IABOMETHOD: "getElderList",
        _DATASOURCE: "ph",
      },
    },
  };

  const {
    data: { body },
  } = await cloudAxios({
    url: "/PhDispatchAction.do",
    method: "post",
    data,
  });
  const {
    dataStores: {
      "felder_main_list.mainGridStore": { rowSet },
    },
  } = body;
  const { primary } = rowSet;
  if (primary.length === 1) {
    return primary[0];
  } else {
    return null;
  }
}

async function getExistedChineseMedicine(code, date, unieap) {
  const data = {
    header: { code: 0, message: { title: "", detail: "" } },
    body: {
      dataStores: {},
      parameters: {
        code,
        _IABONAME: "fhrElderIABO",
        _IABOMETHOD: "getElderTCMByCode",
        _DATASOURCE: "ph",
      },
    },
  };
  const res = await cloudAxios({
    url: "PhDispatchAction.do",
    method: "post",
    data,
  });

  const {
    body: { dataStores },
  } = res.data;
  const {
    "felder_tcm.mainDataStore": {
      rowSet: { primary },
    },
  } = dataStores;

  return primary.find((item) => item.assessdate === dayjs(date).unix() * 1000);
}

async function getDataStore(chid) {
  const data = {
    header: { code: 0, message: { title: "", detail: "" } },
    body: {
      dataStores: {},
      parameters: {
        chid,
        _IABONAME: "fhrElderIABO",
        _IABOMETHOD: "getElderTCMByChid",
        _DATASOURCE: "ph",
      },
    },
  };

  const res = await cloudAxios({
    url: "PhDispatchAction.do",
    method: "post",
    data,
  });

  const {
    body: { dataStores },
  } = res.data;
  return dataStores;
}

async function deleteChineseMedicine(dataStores) {
  const data = {
    header: { code: 0, message: { title: "", detail: "" } },
    body: {
      dataStores,
      parameters: {
        _IABONAME: "fhrElderIABO",
        _IABOMETHOD: "deleteElderTCM",
        _DATASOURCE: "ph",
      },
    },
  };

  await cloudAxios({
    url: "PhDispatchAction.do",
    method: "post",
    data,
  });
}

async function getPersonInfo(code) {
  const data = {
    header: { code: 0, message: { title: "", detail: "" } },
    body: {
      dataStores: {
        "fcom_checkOperType.paramsStore": {
          rowSet: {
            primary: [
              {
                subsystem: "CHSS",
                code,
                managetype: "",
                linkchid: "",
                tablename: "FHR_ELDER_MAIN",
              },
            ],
            filter: [],
            delete: [],
          },
          name: "fcom_checkOperType.paramsStore",
          pageNumber: 1,
          pageSize: 2147483647,
          recordCount: 1,
        },
      },
      parameters: {
        _IABONAME: "fhrElderIABO",
        _IABOMETHOD: "getElderMainInitData",
        _DATASOURCE: "ph",
      },
    },
  };

  const res = await cloudAxios({
    url: "PhDispatchAction.do",
    method: "post",
    data,
  });

  const {
    body: { dataStores },
  } = res.data;
  const {
    "felder_main.personInfo": {
      rowSet: { primary: personStore },
    },
  } = dataStores;
  return personStore;
}

async function getGuideArr() {
  const data = {
    header: { code: 0, message: { title: "", detail: "" } },
    body: {
      dataStores: {
        "sysytem_health_template.healthTemplateStore": {
          rowSet: { primary: [], filter: [], delete: [] },
          name: "sysytem_health_template.healthTemplateStore",
          pageNumber: 1,
          pageSize: 2147483647,
          recordCount: 0,
        },
      },
      parameters: {
        _IABONAME: "systemHealthTemptateIABO",
        _IABOMETHOD: "query",
        _DATASOURCE: "his",
      },
    },
  };
  const res = await cloudAxios({
    url: "PhDispatchAction.do",
    method: "post",
    data,
  });

  const {
    body: { dataStores },
  } = res.data;
  const {
    "sysytem_health_template.healthTemplateStore": {
      rowSet: { primary },
    },
  } = dataStores;

  return primary;
}

async function createChineseMedicine(data) {
  try {
    const res = await cloudAxios({
      url: "PhDispatchAction.do",
      method: "post",
      data,
    });
    if (res.data.header.message.title) {
      return setStatusAndNote(STATUS.WRONG, res.data.header.message.title);
    } else {
      return setStatusAndNote(STATUS.FINISH);
    }
  } catch (err) {
    return setStatusAndNote(STATUS.WRONG, err);
  }
}

export default main;
